package com.mjk.manager.monitor.logger;

import com.mjk.common.tools.springextend.BeeApplicationListener;
import com.mjk.common.tools.springextend.BeeSpringBean;
import com.mjk.manager.monitor.logger.dto.LoggerMessage;
import com.mjk.manager.monitor.logger.queue.LoggerQueue;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.messaging.SessionConnectedEvent;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 基于websocket的监控日志
 */
@Configuration
@EnableWebSocketMessageBroker
public class MonitorLoggerWithWebSocketConfig implements WebSocketMessageBrokerConfigurer, BeeApplicationListener {

    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    private Boolean havingConnect = false;

    /**
     * 配置WebSocket消息代理端点，即stomp服务端;spring boot自带的webSocket模块提供stomp的服务端
     */
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/websocket")
                .setAllowedOriginPatterns("*")

                .withSockJS();
    }

    @Override
    public void doApplicationEvent(ContextRefreshedEvent event) {
        SimpMessagingTemplate messagingTemplate = BeeSpringBean.getBean(SimpMessagingTemplate.class);
        scheduler.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                if (havingConnect) {
                    while (!LoggerQueue.getInstance().isEmpty()) {
                        LoggerMessage log = LoggerQueue.getInstance().poll();
                        if (log != null && messagingTemplate != null) {
                            messagingTemplate.convertAndSend("/topic/pullLogger", log);
                        }
                    }
                }
            }
        }, 0, 1, TimeUnit.SECONDS);
    }

    @EventListener
    private void handleWebSocketConnectListener(SessionConnectedEvent event) {
        havingConnect = true;
    }
}
